package com.front.web.shiro.filter;

import java.util.Iterator;

import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.apache.shiro.web.util.WebUtils;
import org.crazycake.shiro.RedisSessionDAO;
import org.springframework.beans.factory.annotation.Autowired;

import com.front.common.StringUtils;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

public class KickoutSessionControlFilter extends AccessControlFilter
{

    // 踢出后到的地址
    private String kickoutUrl;

    // 踢出之前登录的/之后登录的用户 默认踢出之前登录的用户
    private boolean kickoutAfter = false;

    // 同一个帐号最大会话数 默认1
    private int maxSession = 1;

   @Autowired
    private RedisSessionDAO sessionDao;

    public void setKickoutUrl(String kickoutUrl)
    {
        this.kickoutUrl = kickoutUrl;
    }

    public void setKickoutAfter(boolean kickoutAfter)
    {
        this.kickoutAfter = kickoutAfter;
    }

    public void setMaxSession(int maxSession)
    {
        this.maxSession = maxSession;
    }


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue)
            throws Exception
    {
        return false;
    }

    /***
     * 
     * @param cuurentSession
     * @throws Exception
     */
    private void kickout(Session cuurentSession)throws Exception
    { 
    	Session session = null;
    	Object loginName = cuurentSession.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
    	if(loginName!=null&&!StringUtils.isEmpty(loginName))
    	{
        Iterator<Session>iter= sessionDao.getActiveSessions().iterator();
    	while(iter.hasNext())
    	{
    		session = iter.next();
    		if(session.getId()!=null&&!StringUtils.equals(cuurentSession.getId().toString(), session.getId().toString()))
    		{
    			 Object userName = session.getAttribute("org.apache.shiro.subject.support.DefaultSubjectContext_PRINCIPALS_SESSION_KEY");
                 if(StringUtils.equals(StringUtils.obj2String(userName), StringUtils.obj2String(loginName)))
                 {
                     session.setAttribute("kickout", true);
                     sessionDao.update(session);
                	 break;
                 }
    		}
    	}
    	}
    }
    
    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception
    {
        Subject subject = getSubject(request, response);
        if (!subject.isAuthenticated() && !subject.isRemembered())
        {
            // 如果没有登录，直接进行之后的流程
            return true;
        }
        Session session = subject.getSession();  
        if(session.getAttribute("kickout")==null)
        {
        	kickout(session);
        }
        // 如果被踢出了，直接退出，重定向到踢出后的地址
        if (null != session.getAttribute("kickout"))
        {
            // 会话被踢出了
            try
            {
                subject.logout();
            }
            catch (Exception e)
            { 
                // ignore
            }
            saveRequest(request);
            WebUtils.issueRedirect(request, response, kickoutUrl);
            return false;
        }
        return true;
        }
    // }
}
